<template>
  <div class="execution" style="height:100%">
    <basic-container>
      <avue-crud
        ref="crud"
        :data="sumDataResult ? [...tableData, sumDataResult] : tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"   
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
      >
        <!-- 可修改列 -->
        <template
          v-for="item in slotCols"
          slot-scope="{ row }"
          :slot="item.prop"
        >
          <span :key="item.prop" v-if="row.$index < tableData.length">
            <avue-input-number
              v-model="row[item.prop]"
              :precision="2"
              :disabled="!!item.editDisabled"
            ></avue-input-number>
          </span>
          <span :key="item.prop" v-else>
            {{ row[item.prop] }}
          </span>
        </template>
        <!-- TODO 可修改，自动计算合计 -->
        <!-- <template
          slot="searchMenu"
          slot-scope="{row,size}"
        >
          <el-button
            v-if="permissionList.export"
            @click="exportClick(row)"
          >导出</el-button>
        </template> -->
        <template slot="menuRight">
          刷卡消费：<el-input-number v-model="catTicketPayCard" :precision="4"></el-input-number>
          交通一卡通：<el-input-number v-model="allOneTrafficCard" :precision="4"></el-input-number>
          <el-button v-if="permissionList.export" @click="exportClick"
            >导出</el-button
          >
          <el-button
            v-if="permissionList.editBtn"
            type="primary"
            size="small"
            @click="save"
            >调账保存</el-button>
         <!--
	        <el-button
            v-if="permissionList.confirm"
            type="primary"
            size="small"
            @click="confirm"
            >一键确认</el-button>
          <el-button
            v-if="permissionList.confirmMany"
            type="primary"
            size="small"
            @click="confirmOpen"
            >批量确认</el-button> -->
           
        </template>
      </avue-crud>
      <open-dialog
        :DialogVisible.sync="editVisableDialog"
        title="批量确认"
        width="40%"
      >
        <el-form label-width="60px" v-if="editVisableDialog">
          <avue-form
            v-model="formCreate"
            :option="confrmOption"
            style="margin-bottom: 40px"
          ></avue-form>
          <div class="bottom-menu-report">
            <el-button type="primary" @click="confirmClick()">确认</el-button>
            <el-button type="primary" @click="editVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchLineList } from "@/api/rca/dict";
import {
  fetchList,
  confirmBatch,
  confirmMany,
  dataExport,
  updateBatch
} from "@/api/rca/swckstationdailyreportadjust";
import { tableOption } from "@/const/crud/rca/swckstationdailyreportadjust";
import { handleExcelResponse, getQueryString, deepClone } from "@/util/util";
import { dateFormat } from "@/util/date";
import { treeToList, rcaNumberFormat, multiBigInt } from "@/const/crud/rca/common";
import { mapGetters } from "vuex";

export default {
  name: "swckstationdailyreportadjust",
  data() {
    return {
      searchForm: {
        tradeDate: dateFormat(new Date(), "yyyy-MM-dd"),
        lineCode: "1"
      },
      tableData: [],
      sumData: [],
      tableLoading: false,
      tableOption: tableOption,
      lineOptions: [],
      editVisableDialog: false,
      formCreate: {},
      catTicketPayCard: 0,
      allOneTrafficCard: 0
    };
  },
  computed: {
    slotCols() {
      const copy = deepClone(tableOption);
      return treeToList(copy.column).filter(col => col.slot);
    },
    numberCols() {
      const copy = deepClone(tableOption);
      return treeToList(copy.column).filter(col => col.showSummary);
    },
    sumDataResult() {
      const { tableData, sumData } = this;
      if (tableData.length < 1) {
        return undefined;
      }
      const sum = sumData;
      this.numberCols.forEach(col => {
        if (col.slot) {
          sum[col.prop] = rcaNumberFormat(tableData
            .map(data => data[col.prop])
            .reduce((total, val) => total + val, 0));
        } else {
          sum[col.prop] = rcaNumberFormat(tableData.reduce((total, val) => {
            const sum = Number(col.formatter(val));
            return total + sum;
          }, 0));
        }
      });
      sum.stationCode = "合计";
      return sum;
    },
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        export: this.vaildData(
          this.permissions.sw_ck_station_daily_report_export,
          false
        ),
        confirm: this.vaildData(
          this.permissions.sw_ck_station_daily_report_confirm,
          false
        ),
        confirmMany: this.vaildData(
          this.permissions.sw_ck_station_daily_report_confirmMany,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.sw_ck_station_daily_report_edit,
          false
        )
      };
    },
    confrmOption(){
      return {
        emptyBtn: false,
        submitBtn: false,
        column: [{
          "type": "date",
          "label": "开始日期",
          "prop": "startDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择开始日期',
              trigger: 'blur'
            }
          ]
        }, {
          "type": "date",
          "label": "结束日期",
          "prop": "endDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择结束日期',
              trigger: 'blur'
            }
          ]
        },{
          type: "select",
          label: "线路",
          prop: "lineCodes",
          props: {
            label: 'name',
            value: 'code'
          },
          filterable: true,
          dicUrl: "/support/swparamline/dictsecondname",
          multiple: true,
          rules: [
            {
              required: true,
              message: "请选择一条或多条线路"
            }
          ],
        }]
      }
    }
  },
  created() {
    this.loadLine();
  },
  mounted() {
    this.tableOption.height = this.$el.offsetHeight - 160;
  },
  methods: {
    async loadLine() {
      const { data } = await fetchLineList({});
      this.lineOptions = data.data || [];
    },
    async getList(params = {}) {
      if (!this.searchForm.tradeDate) {
        this.$message.error("结算时间不能为空");
        return;
      }
      if (!this.searchForm.lineCode) {
        this.$message.error("线路不能为空");
        return;
      }
      this.tableLoading = true;
      try {
        const response = await fetchList(
          Object.assign(params, this.searchForm)
        );
        const { numberCols } = this;
        const data = response.data.data.filter(d => d.stationCode !== "999999");
        const sum = response.data.data.find(d => d.stationCode === "999999");
        sum.stationCode = "合计";
        this.tableData = data.map(item => {
          numberCols
            .map(c => c.prop)
            .forEach(col => {
              item[col] = item[col] / 100;
            });
          return item;
        });
        this.sumData = [sum].map(item => {
          numberCols
            .map(c => c.prop)
            .forEach(col => {
              item[col] = item[col] / 100;
            });
            this.catTicketPayCard = item.catTicketPayCard;
            this.allOneTrafficCard = item.allOneTrafficCard;
          return item;
        });
        this.tableLoading = false;
      } catch (e) {
        this.tableLoading = false;
      }
    },
    async searchChange(form, done) {
      this.searchForm = { ...form };
      try {
        await this.getList(this.searchForm);
      } finally {
        done();
      }
    },
    async save() {
      const tableData = deepClone(this.tableData);
      const { numberCols } = this;
      const params = tableData.map(item => {
        numberCols
          .map(c => c.prop)
          .forEach(col => {
            //item[col] = item[col] * 100;
            item[col] = multiBigInt(item[col],100);
          });
        return item;
      });
      let catTicketPayCard = this.catTicketPayCard * 100;
      let allOneTrafficCard = this.allOneTrafficCard * 100;
      await updateBatch(params,catTicketPayCard,allOneTrafficCard);
      this.$message.success("调整保存成功");
      await this.refreshChange();
    },
    async confirm() {//单确认
      // const tableData = deepClone(this.tableData);
      // const { numberCols } = this;
      // const params = tableData.map(item => item.id);
      // await confirmBatch({ swCkStationDailyReportIdList: params });
      if (!this.searchForm.tradeDate) {
        this.$message.error("结算时间不能为空");
        return;
      }
      if (!this.searchForm.lineCode) {
        this.$message.error("线路不能为空");
        return;
      }
      await confirmBatch(this.searchForm);
      this.$message.success("一键确认成功");
      await this.refreshChange();
    },

    confirmOpen(){
      this.editVisableDialog = true;
    },
    confirmClick(){//多确认
      confirmMany(this.formCreate)
        .then(data => {
          this.$message.success('批量确认成功！')
          this.editVisableDialog=false
          this.getList();
        }).catch(() => {
        }); 
    },
    async refreshChange() {
      console.log("refreshChange");
      this.getList();
    },
    async exportClick(row) {
      // await this.searchChange(row, () => { });
      this.dataExport();
    },
    async dataExport() {
      if (!this.searchForm.tradeDate) {
        this.$message.error("结算时间不能为空");
        return;
      }
      if (!this.searchForm.lineCode) {
        this.$message.error("线路不能为空");
        return;
      }
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        const res = await dataExport(this.searchForm);
        // const line = this.lineOptions.find(i => i.code === lineCode)
        // handleExcelResponse(res, `[${tradeDate}]${line.name}导出.xlsx`);
        handleExcelResponse(res);
      } finally {
        loading.close();
      }
    },
    searchReset() {
      this.getList();
    }
  }
};
</script>
<style lang="scss">
.bottom-menu-report {
  margin-top: -30px;
  text-align: center;
}
</style>
